<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>Range Get Position</title>
</head>

<body>
<input onmouseup="getPos();" type="text" value="some text,and some words" />
<div onmouseup="getPos();" id="test" >some words and text</div>
<div id="result" style="border:1px solid red;color:red;width:200px;"></div>
<script>
function $(id){return document.getElementById(id)}
function getPos(){
	var aElem = document.activeElement
	if(document.addEventListener){
		if(aElem&&(aElem.tagName.toLowerCase()=='textarea'||aElem.tagName.toLowerCase()=='input')){
			var s = aElem.selectionStart,e = aElem.selectionEnd;
		}else{
			var selection = window.getSelection().getRangeAt(0)
			var s = selection.startOffset,e = selection.endOffset;
		}
	}else{
		var range = document.selection.createRange()
		if(aElem&&(aElem.tagName.toLowerCase()=='textarea'||aElem.tagName.toLowerCase()=='input')){
			var t_range = range.duplicate();
			t_range.moveEnd('character',aElem.value.length);
			var s = aElem.value.lastIndexOf(t_range.text);
			var t_range = range.duplicate();
			t_range.moveStart('character',-aElem.value.length)
			var e = t_range.text.length;
		}else{
			var t_range = document.body.createTextRange();
			t_range.moveToElementText($('test'))
			t_range.setEndPoint('EndToStart',range)
			var s = t_range.text.length
			t_range.setEndPoint('EndToEnd',range)
			var e = t_range.text.length
		}
	}
	
	$('result').innerHTML = "Start:"+s+'; End:'+e
}
</script>
</body>
</html>
